package com.climb.moive.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/*
* 数据库连接池管理
* */
public class JdbcUtils {
    //声明数据源用于获取
    private static DataSource dataSource;
    //声明一个静态方法，只造一次池子
    static {
        Properties properties=new Properties();
        try {
            properties.load(JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            //对这个数据源进行填充
            dataSource=(DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static DataSource getDataSource() throws SQLException {
        return dataSource;
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public static void close(Connection con) {
        if (con == null) {
            return;
        }
        try {
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Statement stat) {
        if (stat == null) {
            return;
        }
        try {
            stat.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(ResultSet rs) {
        if (rs == null) {
            return;
        }
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection con, Statement stat, ResultSet rs) {
        close(rs);
        close(stat);
        close(con);
    }

}
